import webstomp from 'webstomp-client'
import store from '@/store'
import _ from 'lodash'

//export const MQTT_SERVICE = `ws://${location.hostname}:15674/ws`; // mqtt服务地址
export const MQTT_SERVICE = `ws://localhost:15674/ws` // mqtt服务地址

export const MQTT_USERNAME = 'zhaoming' // mqtt连接用户名
export const MQTT_PASSWORD = '123456' // mqtt连接密码

export const connect = (failCallback = null) => {
  const client = webstomp.client(MQTT_SERVICE, {
    debug: false,
    heartbeat: {
      outgoing: 1000, // 发送心跳包的间隔时间（以毫秒为单位）
      incoming: 1000, // 接收心跳包的超时时间（以毫秒为单位）
    },
    reconnectDelay: -1, // 禁止自动重连
  })

  // 模拟socket发送数据
  // let v = 1
  // setInterval(() => {
  //   v += 1
  //   store.dispatch("app/setSocket", {
  //     key: 'SET_SOCKET_EX',
  //     value: {
  //       title: "station_state:119:OP10", msg: "2023-05-16 13:15:40OP10等待压紧结束"
  //     }
  //   });
  // }, 1000)

  client.hasDebug = false
  return new Promise((resolve, reject) => {
    client.connect(
      MQTT_USERNAME,
      MQTT_PASSWORD,
      () => {
        resolve(client)
      },
      (res) => {
        failCallback && failCallback()
        reject(res)
      }
    )
  })
}

export const subscriber = (client, url) => {
  const subscriberArr = [
    {
      url: 'mq.web.fanout.queue',
      key: 'SET_SOCKET_EX',
    },
  ]
  subscriberArr.map((item) => {
    client.subscribe(
      item.url,
      (res) => {
        // res.nack(res.headers["message-id"]);
        let message = null
        try {
          message = decodeURIComponent(res.body)
        } catch (error) {
          try {
            message = unescape(res.body)
          } catch (error) {
            message = null
            console.error('无法解析：', res.body)
          }
        }

        if (message) {
          try {
            const value = JSON.parse(unescape(message))
            store.dispatch('app/setSocket', {
              key: item.key,
              value,
            })
          } catch (error) {
            console.error('无法解析：', error, message)
          }
        }
        // client.send(item.url, { "content-type": "text/plain" }, res.body);
      },
      (res) => {
        console.log('订阅失败', res)
      }
    )
  })
}
